const { create, update, get, query } = require('../../helper/db');
const { door, ok, now } = require('../../helper/util');

/**
 * @apiDefine ErrorResponse
 * @apiError (请求错误) {String} err_message 错误信息描述
 */

/**
 * @apiVersion 1.0.0
 * @apiGroup 好友
 * @api {POST} api/friend/confirm 确认添加好友
 * @apiName api/friend/confirm
 * @apiExample {js} axios 例子:
 *  axios.post('http://39.105.38.34:8080/api/friend/confirm', {
 *    relationID: 1,
 *  });
 * @apiParam  {String} relationID 申请中的好友关系的 ID
 * @apiSuccess (请求成功) {Null} data 请求成功后不会返回数据
 * @apiuse  ErrorResponse
 */

module.exports = async ctx => {
  var token = ctx.headers.authorization;
  var params = ctx.request.body;
  var user = await door(token);
  var relation = await get('relation_ship', params.relationID);
  var relation = await update('relation_ship', { ...relation, status: 2 });
  var relationlist = await query('select * from relation_ship where userid = ? and friendID = ?', [relation.friendID, relation.userid]);

  if (relationlist.length) {
    await update('relation_ship', {
      ...relationlist[0],
      status: 2,
    });

    ctx.body = ok(null);
    return;
  }
  
  var relation = await create('relation_ship', {
    userid: relation.friendID,
    friendID: relation.userid,
    remark: '',
    status: 2, // 1: 申请中, 2: 成功建立好友关系
    createdat: now(),
  });

  ctx.body = ok(null);
}
